<?php

/**
 * Model EmailConfirm
 *
 * @author nguyenmanhluu
 * @since Oct 19, 2013 - 9:48:44 PM
 *  
 * This is the model class for table "{{email_confirm}}".
 *
 * The followings are the available columns in table '{{email_confirm}}':
 * @property integer $id
 * @property string $email
 * @property string $code
 * @property integer $expire
 * @property string $type
 */
class EmailConfirm extends CActiveRecord
{

    const TYPE_BOOKING        = 0;
    const TYPE_PASSWORD_RESET = 1;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return EmailConfirm the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{email_confirm}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('email, code, expire', 'required'),
            array('expire', 'numerical', 'integerOnly' => true),
            array('email,type', 'length', 'max' => 100),
            array('code', 'length', 'max' => 32),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, email, code, expire,type', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'     => 'ID',
            'email'  => Yii::t('main', 'Email'),
            'code'   => Yii::t('main', 'Code'),
            'expire' => Yii::t('main', 'Expire'),
            'type'   => Yii::t('main', 'Type'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('code', $this->code, true);
        $criteria->compare('expire', $this->expire);
        $criteria->compare('type', $this->type);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Send booking confirm email
     * @param string $email email to send
     * @param stirng $name name of customer
     * @param CActiveRecord $apt a single activerecord of Appoint
     * @param CActiveRecord $cus a single activerecord of Customer
     * @param boolean $trialBooking
     */
    static public function send($email, $name, $apt, $cus, $trialBooking = FALSE)
    {
        $confirm = EmailConfirm::model()->find('email=:e AND type=:t', array(
            ':e' => $email,
            ':t' => self::TYPE_BOOKING
        ));

        if ($confirm == null)
        {
            $confirm        = new EmailConfirm();
            $confirm->email = $email;
        }

        $confirm->type   = self::TYPE_BOOKING;
//        $code = rand(10000, 100000);
        $code            = md5(time() . $apt->apt_id);
        $confirm->code   = $code;
//        $confirm->expire = time() + 48 * 60 * 60;
        $confirm->expire = time() + 15 * 60;
        $confirm->save();

        if ($trialBooking)
        {
            $confirm_url = Yii::app()->createAbsoluteUrl('frontend/booking/confirmTrialBooking', array(
                'appoint' => $apt->apt_id,
                'ckey'    => $cus->ckey,
                'code'    => $code
            ));
        }
        else
        {
            $confirm_url = Yii::app()->createAbsoluteUrl('frontend/booking/confirm', array(
                'appoint' => $apt->apt_id,
                'ckey'    => $cus->ckey,
                'code'    => $code
            ));
        }


        $mail = new MyEmail();

        $mail->type   = MyEmail::TYPE_BOOKING_CONFIRM_LINK;
        $mail->to     = $email;
        $mail->params = array(
            MyEmail::CODE_EMAIL                => $email,
            MyEmail::CUSTOMER_NAME             => $name,
            MyEmail::CUSTOMER_EMAIL            => $email,
            MyEmail::CODE_USER_NAME            => $name,
            MyEmail::ORDER_SERVICE             => $apt->service->s_name,
            MyEmail::CODE_BUSINESS             => $apt->service->user->business_name,
            MyEmail::ORDER_DATE                => date('D, F dS, Y', $apt->date),
            MyEmail::ORDER_TIME                => $apt->getStartTime(),
            MyEmail::CUSTOMER_PHONE            => $cus->user->getPhone(),
            MyEmail::ORDER_PRICE               => $apt->service->price,
            MyEmail::ORDER_NOTE                => $apt->note,
            MyEmail::ORDER_STAFF               => $apt->author->getName(),
            MyEmail::MERCHANT_CONTACT_PHONE    => $apt->author->author->office_phone,
            MyEmail::ORDER_DISCOUNT            => '',
            MyEmail::ORDER_TOTAL_MONEY         => $apt->service->price,
            MyEmail::ORDER_SERVICE_ADDRESS     => $apt->service->address,
            MyEmail::ORDER_SERVICE_IMAGE       => $apt->service->get_absolute_image_url_by_size(600, 340),
            MyEmail::LINK_MAP                  => 'https://www.google.com/maps/place/' . 'Singapore+' . $apt->author->author->postal_code,
            MyEmail::CODE_BOOKING_CONFIRM_LINK => $confirm_url,
        );

        ob_start();
        $mail->send();
        Yii::log(ob_get_contents(), 'error', 'SendMail');
        ob_clean();
    }

    /**
     * Send email password reset confirm
     * @param type $email
     * @param type $name
     * @param type $apt_id
     * @param type $ckey
     */
    static public function sendPasswordReset($email, $ckey, $name)
    {
        $confirm = EmailConfirm::model()->find('email=:e AND type=:t', array(
            ':e' => $email,
            ':t' => self::TYPE_PASSWORD_RESET
        ));

        if ($confirm == null)
        {
            $confirm        = new EmailConfirm();
            $confirm->email = $email;
            $confirm->type  = self::TYPE_PASSWORD_RESET;
        }

        $code            = md5(time() . self::TYPE_PASSWORD_RESET);
        $confirm->code   = $code;
        //2hour
        $confirm->expire = time() + 2 * 3600;
        $confirm->save();

        $confirm_url = Yii::app()->createAbsoluteUrl('/frontend/site/passwordConfirm', array(
            'code' => $code,
            'ukey' => $ckey
        ));

        $mail         = new MyEmail();
        $mail->type   = MyEmail::TYPE_CUSTOMER_PASSWORD_RECOVER_CONFIRM;
        $mail->to     = $email;
        $mail->params = array(
            MyEmail::CODE_EMAIL                       => $email,
            MyEmail::CODE_USER_NAME                   => $name,
            MyEmail::CODE_PASSWORD_RESET_CONFIRM_LINK => $confirm_url,
        );

        ob_start();
        $mail->send();
        Yii::log(ob_get_contents(), 'error', 'SendMail');
        ob_clean();
    }

}

/** 
* End file EmailConfirm
*/
